<?php

/**
 * 
 * @author: peng.shan <peng.shan@happyelements.com>
 * @version $Id: Csv.php 300855 2013-02-21 07:40:32Z peng.shan $
 */

class Csv{
    
	 public static function exportCsv($field , $result) 
	 {
		header("Content-type:text/csv; charset=utf-8");
		header("Content-Disposition:attachment;filename=".date('YmdHis').".csv");
		header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
		header('Expires:0');
		header('Pragma:public');
		echo self::arrayToString($field , $result);
	}

	public static function arrayToString($field , $result) 
	{
		if(empty($result)) {
			return self::i("没有符合您要求的数据！");
		}
		//print_r($result);
		//die;
		$data = '';
		foreach ($field as $fk => $fv) {
			$data .= self::i($fv).',';
		}
		$data .= "\n";
		if(!empty($result)) {
			foreach ($result as $rk => $rv) {
				foreach ($field as $fk => $fv) {
					if(isset($rv[$fk]))
						$data .= self::i($rv[$fk]).',';
				}
				$data .= "\n";
			}
		}
		echo $data;
		return $data;
	}

	public static function beforeCsv($str) 
	{
		$str = str_replace("\t",'', $str);
		$str = str_replace("\r",'', $str);
		$str = str_replace("\n",'', $str);
		return $str;
	}

	public static function i($strInput,$flag=true) 
	{
		if($flag) {
			$strInput = str_replace(",", '，', $strInput);
			$strInput = str_replace("/r", '', $strInput);
			$strInput = str_replace("/n", '', $strInput);
		}
		return iconv('UTF-8','GBK//IGNORE',$strInput);//页面编码为utf-8时使用，否则导出的中文为乱码
	}
}